#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

#include "char_drv.h"

#define DEV_NAME        "/dev/chardrv_dev"

#define DATA_NUM        (32)

int main(void)
{
    int fd = -1;
    int status;
    int config = 123;

    printf("[%s +%d %s] start\n", __FILE__, __LINE__, __func__);
    fd = open(DEV_NAME, O_RDWR);
    if (-1 == fd)
    {
        printf("[%s +%d %s] open(%s) failed\n", __FILE__, __LINE__, __func__, DEV_NAME);
		goto err_open;
    }
    else
    {
        printf("[%s +%d %s] open success\n", __FILE__, __LINE__, __func__);
	}

    // 获取设备状态
    if (ioctl(fd, CHAR_DRV_IOCTL_GET_STATUS, &status) < 0) {
        perror("IOCTL_GET_STATUS failed");
    } else {
        printf("[%s +%d %s] Device status: %d\n", __FILE__, __LINE__, __func__, status);
    }    

    // 设置设备配置
    if (ioctl(fd, CHAR_DRV_IOCTL_SET_CONFIG, &config) < 0) {
        perror("IOCTL_SET_CONFIG failed");
    }
    else
    {
        printf("[%s +%d %s] ioctl CHAR_DRV_IOCTL_SET_CONFIG success\n", __FILE__, __LINE__, __func__);
	}

    // 获取设备状态
    if (ioctl(fd, CHAR_DRV_IOCTL_GET_STATUS, &status) < 0) {
        perror("IOCTL_GET_STATUS failed");
    } else {
        printf("[%s +%d %s] Device status: %d\n", __FILE__, __LINE__, __func__, status);
    }

    // 重置设备
    if (ioctl(fd, CHAR_DRV_IOCTL_RESET) < 0) {
        perror("IOCTL_RESET failed");
    }
    else
    {
        printf("[%s +%d %s] ioctl CHAR_DRV_IOCTL_RESET success\n", __FILE__, __LINE__, __func__);
	}

    // 获取设备状态
    if (ioctl(fd, CHAR_DRV_IOCTL_GET_STATUS, &status) < 0) {
        perror("IOCTL_GET_STATUS failed");
    } else {
        printf("[%s +%d %s] Device status: %d\n", __FILE__, __LINE__, __func__, status);
    }
    if (-1 != fd)
    {
        close(fd);
        fd = -1;
    }
    printf("[%s +%d %s] end\n", __FILE__, __LINE__, __func__);

    return 0;
err_open:
    return -1;
}